import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login.vue'
import Home from '../views/home.vue'
import welcome from '../views/welcome.vue'
import Users from '../views/users'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    redirect: '/welcome',
    component: Home,
    children: [
      {
        path: '/welcome',
        component: welcome
      },
      {
        path: '/users',
        component: Users
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 挂载路由导航守卫  ,每一个路由跳转之前触发
// 路由钩子函数
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from代表从那个路径跳转而来
  // next放行
  // 判断用户是否登录
  // 已登录：next()
  // 未登录：强制跳转到登录页
  // 判断是否是登录页
  // 是：next()
  // 否：强制跳转到登录页
  const token = sessionStorage.getItem('token')
  if (token) {
    next()
  } else {
    if (to.path === '/login') return next()
    next('/login')
  }
})

export default router
